package com.xc.service.Impl;

import com.alibaba.fastjson.JSON;
import com.xc.dao.DeptMapper;
import com.xc.pojo.Dept;
import com.xc.service.DeptService;
import com.xc.utils.JedisPoolUtils;
import com.xc.utils.RedisKey;
import com.xc.vo.DeptVo;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import redis.clients.jedis.Jedis;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
@Transactional
public class DeptServiceImpl implements DeptService {
    @Resource
    private DeptMapper deptMapper;

    /**
     * 查询部门列表
     * @param deptVo
     * @return
     */
    public List<Dept> queryDeptList(DeptVo deptVo) {
        return deptMapper.queryDeptList(deptVo);
    }

    /**
     * 添加部门
     * @param dept
     * @return
     */
    public int addDept(Dept dept) {
        //添加的时间
        dept.setCreateDate(new Date());
        int count=deptMapper.addDept(dept);
        if (count>0){
            //清空缓存
            JedisPoolUtils.getJedis().del(RedisKey.DEPT_LIST);
        }
        return count;
    }

    /**
     * 修改部门
     * @param dept
     * @return
     */
    public int updateDept(Dept dept) {
        //修改的时间
        dept.setCreateDate(new Date());
        int count=deptMapper.updateDept(dept);
        if (count>0){
            //清空缓存
            JedisPoolUtils.getJedis().del(RedisKey.DEPT_LIST);
        }
        return count;
    }

    /**
     * 根据部门id删除部门
     * @param id
     * @return
     */
    public int deleteDept(Integer id) {
        int count=deptMapper.deleteDept(id);
        if (count>0){
            //清空缓存
            JedisPoolUtils.getJedis().del(RedisKey.DEPT_LIST);
        }
        return count;
    }

    /**
     * 查询部门数据并进行缓存
     * @return
     */
    public String queryDeptList() {
        //获取Jedis对象
        Jedis jedis = JedisPoolUtils.getJedis();
        //读取缓存中的数据
        String dept_list = jedis.get(RedisKey.DEPT_LIST);
        //如果缓存中没有对应的数据：
        if(StringUtils.isEmpty(dept_list)){
            //1.从数据库中查询数据
            List<Dept> deptList = deptMapper.queryDeptList(null);
            //2.将数据保存到缓存中
            dept_list = jedis.set(RedisKey.DEPT_LIST, JSON.toJSONString(deptList));
        }
        //返回缓存数据
        return dept_list;
    }


}
